<template>
    <div class="gpm-survey">
        <div class="header">
            <h1>{{ gpmConfig.title }}</h1>
            <p class="subtitle">{{ gpmConfig.subtitle }}</p>
            <div class="header-actions">
                <button @click="goToHome" class="home-btn">
                    <span class="home-icon">🏠</span> {{ gpmConfig.buttons.home }}
                </button>
                <button @click="showSettings = true" class="settings-btn">
                    <span class="settings-icon">⚙️</span> {{ gpmConfig.buttons.settings }}
                </button>
            </div>
        </div>

        <!-- 设置页面 -->
        <div class="settings-modal" v-if="showSettings">
            <div class="settings-content">
                <div class="settings-header">
                    <h2>{{ gpmConfig.settings.title }}</h2>
                    <button @click="closeSettings" class="close-btn">×</button>
                </div>

                <div class="settings-form">
                    <div class="form-group">
                        <label>问答编号：<span class="required">*</span></label>
                        <input type="text" v-model="recorderInfo.surveyId" placeholder="请输入问答编号（用于区分不同组的问卷）"
                            maxlength="20">
                        <p class="field-hint">编号用于区分不同组的问卷，建议使用如：GPM001、PAIN_A等格式</p>
                    </div>
                    <div class="form-group">
                        <label>记录人姓名：<span class="required">*</span></label>
                        <input type="text" v-model="recorderInfo.name" placeholder="请输入记录人姓名">
                    </div>
                    <div class="form-group">
                        <label>记录人职务/身份：<span class="required">*</span></label>
                        <input type="text" v-model="recorderInfo.position" placeholder="请输入职务或身份（如：医生、护士、研究员等）">
                    </div>
                    <div class="form-group">
                        <label>所属机构：</label>
                        <input type="text" v-model="recorderInfo.institution" placeholder="请输入所属医院或机构名称">
                    </div>
                    <div class="form-group">
                        <label>联系方式：</label>
                        <input type="text" v-model="recorderInfo.contact" placeholder="请输入联系电话或邮箱">
                    </div>
                    <div class="form-group">
                        <label>默认备注：</label>
                        <textarea v-model="recorderInfo.defaultRemarks" placeholder="请输入默认备注信息（可选）" rows="3"></textarea>
                    </div>
                </div>

                <div class="settings-actions">
                    <button @click="saveRecorderInfo" class="save-settings-btn">保存设置</button>
                    <button @click="closeSettings" class="cancel-btn">取消</button>
                </div>
            </div>
        </div>

        <!-- 记录人信息显示 -->
        <div class="recorder-info-display" v-if="recorderInfo.name && !showSettings && !showResult && !showExport">
            <div class="recorder-card">
                <div class="recorder-main-info">
                    <h3>问答编号：{{ recorderInfo.surveyId }}</h3>
                    <p>记录人：{{ recorderInfo.name }} | {{ recorderInfo.position }}</p>
                    <p v-if="recorderInfo.institution">{{ recorderInfo.institution }}</p>
                </div>
                <div class="recorder-actions">
                    <button @click="showSettings = true" class="edit-recorder-btn">编辑</button>
                    <button @click="showExportDialog" class="export-btn">{{ gpmConfig.buttons.export }}</button>
                </div>
            </div>
        </div>

        <!-- 导出数据模态框 -->
        <div class="export-modal" v-if="showExport">
            <div class="export-content">
                <div class="export-header">
                    <h2>{{ gpmConfig.export.title }}</h2>
                    <button @click="closeExport" class="close-btn">×</button>
                </div>

                <div class="export-form">
                    <div class="export-info">
                        <p><strong>当前问答编号：</strong>{{ recorderInfo.surveyId }}</p>
                        <p><strong>导出说明：</strong>将从服务器打包当前编号的所有GPM疼痛量表评估数据</p>
                    </div>

                    <div class="form-group">
                        <label>导出密码：<span class="required">*</span></label>
                        <input type="password" v-model="exportPassword" placeholder="请输入导出密码" @keyup.enter="exportData">
                        <p class="field-hint">{{ gpmConfig.messages.passwordHint }}</p>
                    </div>

                    <div class="export-options">
                        <div class="form-group">
                            <label>
                                <input type="checkbox" v-model="exportOptions.includeRawData">
                                包含原始评估数据
                            </label>
                        </div>
                        <div class="form-group">
                            <label>
                                <input type="checkbox" v-model="exportOptions.includeStatistics">
                                包含统计分析
                            </label>
                        </div>
                    </div>
                </div>

                <div class="export-actions">
                    <button @click="exportData" class="export-confirm-btn" :disabled="!exportPassword">
                        <span v-if="!isExporting">导出压缩包</span>
                        <span v-else>导出中...</span>
                    </button>
                    <button @click="closeExport" class="cancel-btn">取消</button>
                </div>
            </div>
        </div>

        <div class="survey-form" v-if="!showResult && !showSettings && !showExport">
            <!-- 被评估人基本信息 -->
            <div class="section">
                <h2>{{ gpmConfig.sections.basicInfo.title }}</h2>
                <div class="form-group" v-for="field in gpmConfig.sections.basicInfo.fields" :key="field.name">
                    <label>{{ field.label }}：<span v-if="field.required" class="required">*</span></label>
                    <input
                        v-if="field.type === 'text' || field.type === 'number' || field.type === 'tel' || field.type === 'datetime-local'"
                        :type="field.type" v-model="formData[field.name]" :placeholder="field.placeholder"
                        :min="field.min" :max="field.max" :step="field.step" :rows="field.rows">
                    <textarea v-else-if="field.type === 'textarea'" v-model="formData[field.name]"
                        :placeholder="field.placeholder" :rows="field.rows"></textarea>
                    <div v-else-if="field.type === 'radio'" class="radio-group">
                        <label v-for="option in field.options" :key="option.value">
                            <input type="radio" v-model="formData[field.name]" :value="option.value"> {{ option.label }}
                        </label>
                    </div>
                </div>
            </div>

            <!-- GPM疼痛量表评估 -->
            <div class="section">
                <h2>{{ gpmConfig.sections.assessment.title }}</h2>
                <p class="assessment-description">{{ gpmConfig.sections.assessment.description }}</p>

                <!-- 各维度评估 -->
                <div v-for="dimension in gpmConfig.sections.assessment.dimensions" :key="dimension.id" class="dimension-section">
                    <h3 class="dimension-title">{{ dimension.title }}</h3>
                    
                    <div class="question-item" v-for="question in dimension.questions" :key="question.id">
                        <h4>{{ question.title }}</h4>
                        <p class="question-desc">{{ question.description }}</p>

                        <!-- 单选题 -->
                        <div v-if="question.type === 'radio'" class="radio-group gpm-options">
                            <label v-for="option in question.options" :key="option.value" class="gmp-option">
                                <input type="radio" v-model="formData[question.field]" :value="option.value">
                                <span class="option-text">{{ option.label }}</span>
                            </label>
                        </div>

                        <!-- 文本域 -->
                        <div v-else-if="question.type === 'textarea'" class="textarea-group">
                            <textarea v-model="formData[question.field]" :placeholder="question.placeholder" :rows="question.rows"></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <div class="submit-section">
                <button @click="calculateResult" class="submit-btn" :disabled="!isFormValid">{{ gpmConfig.buttons.submit }}</button>
            </div>
        </div>

        <!-- 结果展示 -->
        <div class="result-section" v-if="showResult">
            <h2>{{ gpmConfig.result.title }}</h2>
            <div class="result-card">
                <div class="result-summary" :style="{ borderLeftColor: result.painLevelColor }">
                    <h3>{{ result.painLevel }}</h3>
                    <p class="score">{{ gpmConfig.result.totalScore }}：{{ result.totalScore }}/96</p>
                    <p class="range">{{ gpmConfig.result.painLevel }}：{{ result.painLevelRange }}</p>
                </div>

                <div class="result-details">
                    <h4>等级描述：</h4>
                    <p class="level-description">{{ result.description }}</p>
                </div>

                <!-- 各维度得分 -->
                <div class="dimension-scores">
                    <h4>各维度得分：</h4>
                    <div class="dimension-score-grid">
                        <div class="dimension-score-item">
                            <span class="dimension-name">{{ gpmConfig.result.dimension1Score }}</span>
                            <span class="dimension-value">{{ result.dimension1Score }}/20</span>
                            <span class="dimension-severity">{{ result.dimensionAnalysis.dimension1.severity }}</span>
                        </div>
                        <div class="dimension-score-item">
                            <span class="dimension-name">{{ gpmConfig.result.dimension2Score }}</span>
                            <span class="dimension-value">{{ result.dimension2Score }}/28</span>
                            <span class="dimension-severity">{{ result.dimensionAnalysis.dimension2.severity }}</span>
                        </div>
                        <div class="dimension-score-item">
                            <span class="dimension-name">{{ gpmConfig.result.dimension3Score }}</span>
                            <span class="dimension-value">{{ result.dimension3Score }}/24</span>
                            <span class="dimension-severity">{{ result.dimensionAnalysis.dimension3.severity }}</span>
                        </div>
                        <div class="dimension-score-item">
                            <span class="dimension-name">{{ gpmConfig.result.dimension4Score }}</span>
                            <span class="dimension-value">{{ result.dimension4Score }}/16</span>
                            <span class="dimension-severity">{{ result.dimensionAnalysis.dimension4.severity }}</span>
                        </div>
                        <div class="dimension-score-item">
                            <span class="dimension-name">{{ gpmConfig.result.dimension5Score }}</span>
                            <span class="dimension-value">{{ result.dimension5Score }}/8</span>
                            <span class="dimension-severity">{{ result.dimensionAnalysis.dimension5.severity }}</span>
                        </div>
                    </div>
                </div>

                <!-- 主观描述 -->
                <div class="subjective-descriptions" v-if="formData.painDescription || formData.priorityImprovement">
                    <h4>主观描述：</h4>
                    <div v-if="formData.painDescription" class="description-item">
                        <strong>{{ gpmConfig.result.painDescription }}：</strong>
                        <p>{{ formData.painDescription }}</p>
                    </div>
                    <div v-if="formData.priorityImprovement" class="description-item">
                        <strong>{{ gpmConfig.result.priorityImprovement }}：</strong>
                        <p>{{ formData.priorityImprovement }}</p>
                    </div>
                </div>

                <!-- BMI信息 -->
                <div class="bmi-info" v-if="result.bmi">
                    <h4>{{ gpmConfig.result.bmi }}：</h4>
                    <p>{{ result.bmi.value }} ({{ result.bmi.category }})</p>
                </div>

                <div class="result-recommendations">
                    <h4>{{ gpmConfig.result.recommendations }}：</h4>
                    <ul>
                        <li v-for="(rec, index) in result.recommendations" :key="index">{{ rec }}</li>
                    </ul>
                </div>

                <div class="result-explanation">
                    <h4>{{ gpmConfig.result.explanation.title }}：</h4>
                    <p v-for="item in gpmConfig.result.explanation.items" :key="item">{{ item }}</p>
                </div>

                <div class="action-buttons">
                    <button @click="saveToBackendOnly" class="save-btn" :disabled="isSaving">
                        <span v-if="!isSaving">{{ gpmConfig.buttons.save }}</span>
                        <span v-else>{{ gpmConfig.buttons.saving }}</span>
                    </button>
                    <button @click="resetForm" class="reset-btn">{{ gpmConfig.buttons.reset }}</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { gpmConfig } from '@/config/gpmConfig.js';
import { calculateGPMAssessment } from '@/config/gpmLogic.js';

export default {
    name: 'GPMSurvey',
    mounted() {
        // 自动设置当前时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        this.formData.recordTime = `${year}-${month}-${day}T${hours}:${minutes}`;

        // 加载记录人信息
        this.loadRecorderInfo();
    },
    data() {
        return {
            gpmConfig,
            showResult: false,
            showSettings: false,
            showExport: false,
            isExporting: false,
            isSaving: false,
            exportPassword: '',
            // 记录人信息（设置）
            recorderInfo: {
                surveyId: '',
                name: '',
                position: '',
                institution: '',
                contact: '',
                defaultRemarks: ''
            },
            // 导出选项
            exportOptions: gpmConfig.exportOptions,
            // 问卷表单数据
            formData: {
                // 被评估人信息
                patientName: '',
                age: null,
                gender: '',
                height: null,
                weight: null,
                phone: '',
                recordTime: '',
                remarks: '',
                // 维度一：疼痛强度和频率
                restPain: null,
                activityPain: null,
                painFrequency: null,
                nightWakeups: null,
                painDuration: null,
                // 维度二：日常生活活动能力
                dressingAbility: null,
                eatingAbility: null,
                walkingAbility: null,
                toiletingAbility: null,
                hygieneAbility: null,
                sleepQuality: null,
                houseworkAbility: null,
                // 维度三：心理情绪状态
                anxiety: null,
                depression: null,
                irritability: null,
                helplessness: null,
                concentration: null,
                lifeEnjoyment: null,
                // 维度四：社会功能
                socialParticipation: null,
                familyRole: null,
                workAbility: null,
                intimateRelationship: null,
                // 维度五：疼痛管理
                painReliefEffect: null,
                medicalSeeking: null,
                // 维度六：主观描述
                painDescription: '',
                priorityImprovement: ''
            },
            result: {
                totalScore: 0,
                dimension1Score: 0,
                dimension2Score: 0,
                dimension3Score: 0,
                dimension4Score: 0,
                dimension5Score: 0,
                painLevel: '',
                painLevelColor: '',
                painLevelRange: '',
                description: '',
                recommendations: [],
                bmi: null,
                dimensionAnalysis: {}
            }
        }
    },
    computed: {
        isFormValid() {
            // 个人信息字段已改为选填，不再进行必填验证
            
            // 检查必填的评估项目（1-24题）
            const requiredFields = [
                'restPain', 'activityPain', 'painFrequency', 'nightWakeups', 'painDuration',
                'dressingAbility', 'eatingAbility', 'walkingAbility', 'toiletingAbility', 'hygieneAbility', 'sleepQuality', 'houseworkAbility',
                'anxiety', 'depression', 'irritability', 'helplessness', 'concentration', 'lifeEnjoyment',
                'socialParticipation', 'familyRole', 'workAbility', 'intimateRelationship',
                'painReliefEffect', 'medicalSeeking'
            ];
            
            return requiredFields.every(field => {
                const value = this.formData[field];
                return value !== undefined && value !== null && value !== '';
            });
        }
    },
    methods: {
        // 页面导航
        goToHome() {
            this.$router.push('/');
        },

        // 设置相关方法
        closeSettings() {
            this.showSettings = false;
        },

        saveRecorderInfo() {
            // 验证必填字段
            if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
                alert('请填写所有必填信息（问答编号、记录人姓名、职务/身份）！');
                return;
            }

            // 保存到本地存储
            localStorage.setItem('gpm_recorderInfo', JSON.stringify(this.recorderInfo));
            
            // 如果有默认备注，设置到表单中
            if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
                this.formData.remarks = this.recorderInfo.defaultRemarks;
            }

            this.showSettings = false;
            alert(gpmConfig.messages.saveSuccess);
        },

        loadRecorderInfo() {
            const saved = localStorage.getItem('gpm_recorderInfo');
            if (saved) {
                this.recorderInfo = JSON.parse(saved);
                // 如果有默认备注，设置到表单中
                if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
                    this.formData.remarks = this.recorderInfo.defaultRemarks;
                }
            }
        },

        // 导出相关方法
        showExportDialog() {
            if (!this.recorderInfo.surveyId) {
                alert('请先设置问答编号！');
                return;
            }
            this.showExport = true;
        },

        closeExport() {
            this.showExport = false;
            this.exportPassword = '';
        },

        async exportData() {
            if (!this.recorderInfo.surveyId) {
                alert(gpmConfig.messages.requiredFieldsError);
                return;
            }

            if (!this.exportPassword) {
                alert('请输入导出密码！');
                return;
            }

            this.isExporting = true;

            try {
                const response = await fetch('/api/export-gpm-survey', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        surveyId: this.recorderInfo.surveyId,
                        password: this.exportPassword,
                        exportOptions: this.exportOptions
                    })
                });

                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `gpm_survey_${this.recorderInfo.surveyId}_${new Date().toISOString().split('T')[0]}.zip`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    alert(gpmConfig.messages.exportSuccess);
                    this.closeExport();
                } else {
                    if (response.status === 401) {
                        alert(gpmConfig.messages.passwordError);
                    } else if (response.status === 404) {
                        alert(gpmConfig.messages.noDataError);
                    } else {
                        alert(gpmConfig.messages.exportError);
                    }
                }
            } catch (error) {
                console.error('导出失败:', error);
                alert(gpmConfig.messages.exportError);
            } finally {
                this.isExporting = false;
            }
        },

        // 评估计算
        calculateResult() {
            if (!this.isFormValid) {
                alert('请完成所有必填项目！');
                return;
            }

            // 计算评估结果
            const assessmentResult = calculateGPMAssessment(this.formData);
            this.result = assessmentResult;
            this.showResult = true;
        },

        // 保存到后台
        async saveToBackendOnly() {
            if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
                alert(gpmConfig.messages.requiredFieldsError);
                return;
            }

            this.isSaving = true;

            try {
                const response = await fetch('/api/save-gpm-survey', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        surveyId: this.recorderInfo.surveyId,
                        recorderName: this.recorderInfo.name,
                        recorderPosition: this.recorderInfo.position,
                        recorderInstitution: this.recorderInfo.institution,
                        recorderContact: this.recorderInfo.contact,
                        ...this.formData,
                        patientName: this.formData.patientName || "未填写",
                        age: this.formData.age || 0,
                        // 添加计算结果字段
                        totalScore: this.result.totalScore,
                        dimension1Score: this.result.dimension1Score,
                        dimension2Score: this.result.dimension2Score,
                        dimension3Score: this.result.dimension3Score,
                        dimension4Score: this.result.dimension4Score,
                        dimension5Score: this.result.dimension5Score,
                        painLevel: this.result.painLevel,
                        painLevelRange: this.result.painLevelRange,
                        recommendations: this.result.recommendations,
                        createdAt: new Date().toISOString()
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '未知错误');
                }

                // 2. 生成评估报告内容
                const reportContent = this.generateGPMReport();

                // 3. 保存评估报告到@data/文件夹
                await this.saveFileToDataFolder(reportContent);

                alert('✅ 数据已成功保存到后台！\n\n📁 问卷数据：survey_data/\n📄 评估报告：@data/');
            } catch (error) {
                console.error('保存失败:', error);
                alert(gpmConfig.messages.saveError + error.message);
            } finally {
                this.isSaving = false;
            }
        },

        generateGPMReport() {
            const timestamp = new Date().toLocaleString('zh-CN');
            const recordTime = this.formData.recordTime ?
                new Date(this.formData.recordTime).toLocaleString('zh-CN') :
                timestamp;

            return `GPM疼痛量表评估结果报告
问答编号：${this.recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${this.recorderInfo.name}
记录人职务/身份：${this.recorderInfo.position}
所属机构：${this.recorderInfo.institution}
联系方式：${this.recorderInfo.contact}
记录时间：${recordTime}
备注：${this.formData.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${this.formData.patientName}
年龄：${this.formData.age}岁
性别：${this.formData.gender === 'male' ? '男性' : '女性'}
身高：${this.formData.height || '未填写'}cm
体重：${this.formData.weight || '未填写'}kg
联系电话：${this.formData.phone || '未填写'}

=== 评估结果总览 ===
疼痛等级：${this.result.painLevel}
总分：${this.result.totalScore}/96
疼痛等级范围：${this.result.painLevelRange}
等级描述：${this.result.description}

=== 各维度得分详情 ===
维度一（疼痛强度和频率）：${this.result.dimension1Score}/20 - ${this.result.dimensionAnalysis.dimension1?.severity || '未评估'}
维度二（日常生活活动能力）：${this.result.dimension2Score}/28 - ${this.result.dimensionAnalysis.dimension2?.severity || '未评估'}
维度三（心理情绪状态）：${this.result.dimension3Score}/24 - ${this.result.dimensionAnalysis.dimension3?.severity || '未评估'}
维度四（社会功能）：${this.result.dimension4Score}/16 - ${this.result.dimensionAnalysis.dimension4?.severity || '未评估'}
维度五（疼痛管理）：${this.result.dimension5Score}/8 - ${this.result.dimensionAnalysis.dimension5?.severity || '未评估'}

=== 具体评估项目 ===
维度一：疼痛强度和频率
- 静息时疼痛：${this.formData.restPain || '未填写'}
- 活动时疼痛：${this.formData.activityPain || '未填写'}
- 疼痛频率：${this.formData.painFrequency || '未填写'}
- 夜间醒来次数：${this.formData.nightWakeups || '未填写'}
- 疼痛持续时间：${this.formData.painDuration || '未填写'}

维度二：日常生活活动能力
- 穿衣能力：${this.formData.dressingAbility || '未填写'}
- 进食能力：${this.formData.eatingAbility || '未填写'}
- 行走能力：${this.formData.walkingAbility || '未填写'}
- 如厕能力：${this.formData.toiletingAbility || '未填写'}
- 个人卫生：${this.formData.hygieneAbility || '未填写'}
- 睡眠质量：${this.formData.sleepQuality || '未填写'}
- 家务能力：${this.formData.houseworkAbility || '未填写'}

维度三：心理情绪状态
- 焦虑程度：${this.formData.anxiety || '未填写'}
- 抑郁程度：${this.formData.depression || '未填写'}
- 易怒程度：${this.formData.irritability || '未填写'}
- 无助感：${this.formData.helplessness || '未填写'}
- 注意力集中：${this.formData.concentration || '未填写'}
- 生活乐趣：${this.formData.lifeEnjoyment || '未填写'}

维度四：社会功能
- 社会参与：${this.formData.socialParticipation || '未填写'}
- 家庭角色：${this.formData.familyRole || '未填写'}
- 工作能力：${this.formData.workAbility || '未填写'}
- 亲密关系：${this.formData.intimateRelationship || '未填写'}

维度五：疼痛管理
- 疼痛缓解效果：${this.formData.painReliefEffect || '未填写'}
- 就医行为：${this.formData.medicalSeeking || '未填写'}

=== 主观描述 ===
疼痛描述：${this.formData.painDescription || '无'}
优先改善方面：${this.formData.priorityImprovement || '无'}

=== BMI信息 ===
${this.result.bmi ? `BMI：${this.result.bmi.value} (${this.result.bmi.category})` : 'BMI：未计算'}

=== 建议措施 ===
${this.result.recommendations ? this.result.recommendations.map((rec, index) => `${index + 1}. ${rec}`).join('\n') : '无'}

报告结束
`;
        },

        async saveFileToDataFolder(content) {
            // 通过API保存文件到@data/文件夹
            const filename = `GPM疼痛量表评估结果_${this.recorderInfo.surveyId}_${this.formData.patientName}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;

            const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-file`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    filename: filename,
                    content: content,
                    surveyId: this.recorderInfo.surveyId
                })
            });

            if (!response.ok) {
                throw new Error('保存评估报告失败');
            }
        },

        // 重置表单
        resetForm() {
            if (confirm('确定要重新开始评估吗？这将清除当前所有数据。')) {
                // 重置表单数据，但保留基本信息
                const basicInfo = {
                    patientName: '',
                    age: null,
                    gender: '',
                    height: null,
                    weight: null,
                    phone: '',
                    recordTime: this.formData.recordTime,
                    remarks: this.recorderInfo.defaultRemarks || ''
                };
                
                this.formData = {
                    ...basicInfo,
                    // 重置所有评估项目
                    restPain: null,
                    activityPain: null,
                    painFrequency: null,
                    nightWakeups: null,
                    painDuration: null,
                    dressingAbility: null,
                    eatingAbility: null,
                    walkingAbility: null,
                    toiletingAbility: null,
                    hygieneAbility: null,
                    sleepQuality: null,
                    houseworkAbility: null,
                    anxiety: null,
                    depression: null,
                    irritability: null,
                    helplessness: null,
                    concentration: null,
                    lifeEnjoyment: null,
                    socialParticipation: null,
                    familyRole: null,
                    workAbility: null,
                    intimateRelationship: null,
                    painReliefEffect: null,
                    medicalSeeking: null,
                    painDescription: '',
                    priorityImprovement: ''
                };
                
                this.showResult = false;
            }
        }
    }
}
</script>

<style scoped>
/* 基础样式 */
.gmp-survey {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    line-height: 1.6;
    color: #333;
}

/* 头部样式 */
.header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.header h1 {
    margin: 0 0 10px 0;
    font-size: 2.5em;
    font-weight: 300;
}

.subtitle {
    margin: 0 0 20px 0;
    font-size: 1.1em;
    opacity: 0.9;
}

.header-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
}

.home-btn, .settings-btn {
    padding: 10px 20px;
    background: rgba(255, 255, 255, 0.2);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 25px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 14px;
}

.home-btn:hover, .settings-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-2px);
}

/* 模态框样式 */
.settings-modal, .export-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.settings-content, .export-content {
    background: white;
    padding: 30px;
    border-radius: 15px;
    width: 90%;
    max-width: 600px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.settings-header, .export-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #f0f0f0;
}

.close-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #999;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.close-btn:hover {
    color: #333;
}

/* 表单样式 */
.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
    color: #555;
}

.required {
    color: #e74c3c;
}

.form-group input, .form-group textarea {
    width: 100%;
    padding: 12px;
    border: 2px solid #e1e8ed;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.3s ease;
    box-sizing: border-box;
}

.form-group input:focus, .form-group textarea:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.field-hint {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
    margin-bottom: 0;
}

/* 记录人信息卡片 */
.recorder-info-display {
    margin-bottom: 30px;
}

.recorder-card {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 10px;
    border-left: 4px solid #667eea;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.recorder-main-info h3 {
    margin: 0 0 5px 0;
    color: #333;
}

.recorder-main-info p {
    margin: 5px 0;
    color: #666;
}

.recorder-actions {
    display: flex;
    gap: 10px;
}

.edit-recorder-btn, .export-btn {
    padding: 8px 16px;
    border: 1px solid #ddd;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

.edit-recorder-btn {
    background: white;
    color: #333;
}

.export-btn {
    background: #28a745;
    color: white;
    border-color: #28a745;
}

.edit-recorder-btn:hover {
    background: #f8f9fa;
}

.export-btn:hover {
    background: #218838;
}

/* 问卷表单样式 */
.section {
    background: white;
    padding: 25px;
    margin-bottom: 25px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.section h2 {
    margin: 0 0 20px 0;
    color: #333;
    font-size: 1.5em;
    border-bottom: 2px solid #667eea;
    padding-bottom: 10px;
}

.assessment-description {
    background: #e8f2ff;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 25px;
    color: #2c5aa0;
    border-left: 4px solid #667eea;
}

/* 维度样式 */
.dimension-section {
    margin-bottom: 30px;
    padding: 20px;
    background: #fafbfc;
    border-radius: 8px;
    border-left: 4px solid #28a745;
}

.dimension-title {
    margin: 0 0 20px 0;
    color: #28a745;
    font-size: 1.3em;
    font-weight: 600;
}

.question-item {
    margin-bottom: 25px;
    padding: 15px;
    background: white;
    border-radius: 8px;
    border: 1px solid #e1e8ed;
}

.question-item h4 {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 1.1em;
}

.question-desc {
    margin: 0 0 15px 0;
    color: #666;
    font-style: italic;
}

/* 选项样式 */
.radio-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.gmp-options .gmp-option {
    display: flex;
    align-items: flex-start;
    padding: 12px;
    border: 2px solid #e1e8ed;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: white;
}

.gmp-options .gmp-option:hover {
    border-color: #667eea;
    background: #f8f9ff;
}

.gmp-options .gmp-option input[type="radio"] {
    margin-right: 12px;
    margin-top: 2px;
}

.option-text {
    flex: 1;
    line-height: 1.5;
}

.textarea-group textarea {
    width: 100%;
    min-height: 80px;
    resize: vertical;
}

/* 提交按钮 */
.submit-section {
    text-align: center;
    margin-top: 30px;
}

.submit-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    padding: 15px 40px;
    font-size: 16px;
    border-radius: 25px;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.submit-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.submit-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
    box-shadow: none;
}

/* 结果展示样式 */
.result-section {
    margin-top: 30px;
}

.result-card {
    background: white;
    padding: 30px;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.result-summary {
    padding: 20px;
    border-radius: 10px;
    background: #f8f9fa;
    border-left: 5px solid #667eea;
    margin-bottom: 25px;
}

.result-summary h3 {
    margin: 0 0 10px 0;
    font-size: 1.8em;
    color: #333;
}

.score, .range {
    margin: 5px 0;
    font-size: 1.1em;
    color: #555;
}

.result-details, .dimension-scores, .subjective-descriptions, .bmi-info, .result-recommendations, .result-explanation {
    margin-bottom: 25px;
}

.result-details h4, .dimension-scores h4, .subjective-descriptions h4, .bmi-info h4, .result-recommendations h4, .result-explanation h4 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 1.2em;
    border-bottom: 1px solid #eee;
    padding-bottom: 5px;
}

.level-description {
    color: #666;
    line-height: 1.6;
}

/* 维度得分网格 */
.dimension-score-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
}

.dimension-score-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
    background: #f8f9fa;
    border-radius: 8px;
    border-left: 4px solid #28a745;
}

.dimension-name {
    font-weight: 500;
    color: #333;
    flex: 1;
}

.dimension-value {
    font-weight: 600;
    color: #667eea;
    margin: 0 10px;
}

.dimension-severity {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
    background: #e8f5e8;
    color: #28a745;
}

/* 主观描述 */
.description-item {
    margin-bottom: 15px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
}

.description-item strong {
    color: #333;
    display: block;
    margin-bottom: 8px;
}

.description-item p {
    margin: 0;
    color: #666;
    line-height: 1.5;
}

/* 建议和说明 */
.result-recommendations ul, .result-explanation {
    color: #666;
    line-height: 1.6;
}

.result-recommendations li {
    margin-bottom: 8px;
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
}

.save-btn, .reset-btn {
    padding: 12px 25px;
    border: none;
    border-radius: 25px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

.save-btn {
    background: #28a745;
    color: white;
}

.reset-btn {
    background: #6c757d;
    color: white;
}

.save-btn:hover:not(:disabled) {
    background: #218838;
    transform: translateY(-2px);
}

.reset-btn:hover {
    background: #5a6268;
    transform: translateY(-2px);
}

.save-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

/* 设置和导出按钮 */
.settings-actions, .export-actions {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    margin-top: 25px;
    padding-top: 20px;
    border-top: 1px solid #eee;
}

.save-settings-btn, .export-confirm-btn {
    background: #667eea;
    color: white;
    border: none;
    padding: 12px 25px;
    border-radius: 25px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.cancel-btn {
    background: #6c757d;
    color: white;
    border: none;
    padding: 12px 25px;
    border-radius: 25px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.save-settings-btn:hover, .export-confirm-btn:hover:not(:disabled) {
    background: #5a6fd8;
    transform: translateY(-2px);
}

.cancel-btn:hover {
    background: #5a6268;
    transform: translateY(-2px);
}

.export-confirm-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

/* 导出信息 */
.export-info {
    background: #e8f2ff;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
    border-left: 4px solid #667eea;
}

.export-info p {
    margin: 5px 0;
    color: #2c5aa0;
}

.export-options {
    margin-top: 20px;
}

.export-options .form-group {
    margin-bottom: 10px;
}

.export-options label {
    display: flex;
    align-items: center;
    cursor: pointer;
}

.export-options input[type="checkbox"] {
    margin-right: 8px;
    width: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .gmp-survey {
        padding: 10px;
    }
    
    .header h1 {
        font-size: 2em;
    }
    
    .header-actions {
        flex-direction: column;
        align-items: center;
    }
    
    .recorder-card {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .recorder-actions {
        width: 100%;
        justify-content: flex-end;
    }
    
    .dimension-score-grid {
        grid-template-columns: 1fr;
    }
    
    .action-buttons {
        flex-direction: column;
        align-items: center;
    }
    
    .settings-content, .export-content {
        width: 95%;
        padding: 20px;
    }
}
</style>